package com.zengqingfa.interview;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zengqingfa
 * @className ABCTest6
 * @description
 * @create 2022/12/3 11:05
 */
public class ABCTest6 {

    private int num;
    private static Lock lock = new ReentrantLock();
    private static Condition condition1 = lock.newCondition();
    private static Condition condition2 = lock.newCondition();
    private static Condition condition3 = lock.newCondition();

    /**
     * 打印ABC
     *
     * @param targetNum
     */
    public void printABC(int targetNum, Condition currentThread, Condition nextThread) {
        for (int i = 0; i < 10; ) {
            lock.lock();
            while (num % 3 != targetNum) {
                try {
                    //阻塞当前线程
                    currentThread.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            num++;
            i++;
            System.out.println(Thread.currentThread().getName());
            //唤醒下一个线程，而不是唤醒所有线程
            nextThread.signal();
            lock.unlock();
        }

    }


    public static void main(String[] args) throws InterruptedException {
        ABCTest6 abcTest6 = new ABCTest6();
        new Thread(() -> {
            abcTest6.printABC(0, condition1, condition2);
        }, "A").start();
        new Thread(() -> {
            abcTest6.printABC(1, condition2, condition3);
        }, "B").start();
        new Thread(() -> {
            abcTest6.printABC(2, condition3, condition1);
        }, "C").start();
    }


}